package com.lry.basic.algorithm.stack;

import java.util.Stack;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/12/6
 */
public class RemoveKdigits {
    public static void main(String[] args) {
        System.out.println(removeKdigits2("1432219", 3));
    } //1 2 2 7


    public static String removeKdigits2(String num,int k){
        while(k>0) {
            for(int i=0;i<num.length();i++) {
                //删除最后一个元素
                if (i == num.length() - 1) {
                    num = num.substring(0, num.length() - 1);
                    k--;
                    break;
                }
                if (num.charAt(i) > num.charAt(i + 1)) {
                    //删除i
                    num = num.substring(0, i) + num.substring(i + 1);
                    k--;
                    break;
                }
            }
        }
        return removeZero(num);
    }

    public static String removeKdigits(String num, int k) {
        if(null==num||num.length()==0||num.length()<k)return "0";
        if(k<=0)return removeZero(num);
        for(int i=0;i<num.length();i++){
            //删除最后一个元素
            if(i==num.length()-1){
                num = num.substring(0,num.length()-1);
                break;
            }
            if(num.charAt(i)>num.charAt(i+1)){
                //删除i
                num = num.substring(0,i)+num.substring(i+1);
                break;
            }
        }
        return removeKdigits(num,--k);
    }
    private static String removeZero(String num){
       if(null==num||num.length()==0)return "0";
       if(num.startsWith("0")){
           return removeZero(num.substring(1));
       }else{
           return num;
       }
    }
}
